package com.servlet.control;

import com.bean.User;
import com.jdbc.util.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(
        name = "loginServlet",
        urlPatterns = {"/loginServlet"})
public class loginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置编码
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();


        // 获取请求参数
        String username = request.getParameter("userName");
        String password = request.getParameter("Pwd");
        String role = request.getParameter("role");

        // System.out.println(username + password + role);

        // 声明数据库操作类
        DButil db = new DButil();
        // 取得数据库连接
        db.getConn();

        // 判断用户名和密码是否正确
        ResultSet rs =
                db.getResultSet(
                        "Select * from user where username = ? and password = ? and role = ?",
                        new String[]{username, password, role});
        try {
            if (!rs.next()) {
                request.setAttribute("message", "登陆失败，请核对用户名，密码和您的角色");
                request.getRequestDispatcher("/index.jsp").forward(request, response);
                //                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                User user = new User(username, password, rs.getString("realname"), role);
                session.setAttribute("user", user);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (role.equals("1")) {
            response.sendRedirect(request.getContextPath() + "/jsp/teacher.jsp");
        } else {
            response.sendRedirect(request.getContextPath() + "/jsp/student.jsp");
        }
    }
}
